package org.szgb.console.sys.user.web;

import cn.hutool.http.HttpStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.szgb.console.sys.user.entity.SysUser;
import org.szgb.console.sys.user.entity.SysUserRole;
import org.szgb.console.sys.user.service.SysUserRoleService;
import org.szgb.console.sys.user.service.SysUserService;
import org.szgb.console.utils.PageView;
import org.szgb.console.utils.TokenUtil;
import org.szgb.core.utils.AjaxJson;

import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/sys/user")
@Tag(name = "用户管理", description = "用户管理模块")
public class SysUserController {
    private final SysUserService sysUserService;
    private final SysUserRoleService sysUserRoleService;

    @Autowired
    public SysUserController(SysUserService sysUserService,SysUserRoleService sysUserRoleService) {
        this.sysUserService = sysUserService;
        this.sysUserRoleService = sysUserRoleService;
    }

    @Operation(summary = "用户登录", description = "用户登录系统，成功后返回 JWT Token 和用户信息。")
    @PostMapping("/login")
    public AjaxJson getLogin(@RequestBody SysUser.SysUserLoginDto sysUserLoginDto, HttpServletRequest request, HttpServletResponse response) {
        SysUser sysUser = sysUserService.getToken(sysUserLoginDto.toSysUser());
        if (sysUser == null) {
            return AjaxJson.error("账号或密码错误", HttpStatus.HTTP_UNAUTHORIZED, request, response);
        }
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUser(sysUser);
        // 获取角色列表
        List<SysUserRole> userRoleList = sysUserRoleService.findList(sysUserRole);
        return AjaxJson.success("操作成功", request, response).put("sysUser", sysUser.toSysUserLoginView(userRoleList));
    }

    @Operation(summary = "获取用户信息", description = "根据查询参数获取用户信息，支持分页查询。使用id获取更详细的信息。")
    @PostMapping("/get")
    public AjaxJson get(@RequestBody(required = false) SysUser.SysUserFindDto sysUserFindDto, HttpServletRequest request, HttpServletResponse response) {
        if(sysUserFindDto == null){
            sysUserFindDto=new SysUser.SysUserFindDto();
        }
        // 创建一个PageView对象，用于分页显示
        PageView<SysUser.SysUserView> pageView = new PageView<>();
        SysUser sysUser = sysUserFindDto.toSysUser();
        // 如果实体对象的ID不为空，则直接调用get方法获取单个实体对象
        if (sysUser != null && sysUser.getId() != null && !sysUser.getId().isEmpty()) {
            SysUser user = sysUserService.get(sysUser.getId());
            // 如果实体对象为空，则返回错误响应
            if (user == null) {
                return AjaxJson.error("数据不存在", HttpStatus.HTTP_NOT_FOUND, request, response);
            }
            // 返回成功的响应，并将实体对象放入响应中
            return AjaxJson.success(request, response).put("sysUser", user.toSysUserView());
        } else {
            // 设置Page对象的列表属性，包含根据实体对象查询到的数据
            pageView.setList(SysUser.SysUserView.getViewListFromList(sysUserService.findList(sysUser)));
            // 设置Page对象的总记录数属性，用于分页显示
            pageView.setCount(sysUserService.getCount(sysUser));
            // 创建一个成功的AjaxJson对象，并放入Page对象，以便于前端展示
            return AjaxJson.success(request, response).put("page", pageView);
        }
    }

    @PostMapping("/get/fuzzy")
    @Operation(summary = "模糊查询用户", description = "根据查询参数模糊查询用户信息。支持用户名、姓名、工号模糊查询", parameters = {@Parameter(name = "parameter", description = "模糊查询参数。")})
    public AjaxJson fuzzyGet(@RequestParam String parameter, HttpServletRequest request, HttpServletResponse response) {
        return AjaxJson.success(request, response).put("sysUserList", SysUser.SysUserView.getViewListFromList(sysUserService.fuzzyGet(parameter)));
    }


    @PostMapping("/save")
    @Operation(summary = "保存用户", description = "新增或更改用户信息。")
    public AjaxJson save(@RequestBody SysUser.SysUserSaveDto sysUserSaveDto, HttpServletRequest request, HttpServletResponse response) {
        if (sysUserSaveDto == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        SysUser sysUser = sysUserSaveDto.toSysUser();
        // 设置实体对象的更新者为当前用户
        sysUser.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        // 调用服务层的save方法，尝试保存或更新实体对象，返回保存结果的Map
        sysUserService.save(sysUser);
        // 根据保存结果返回相应的AjaxJson对象
        return AjaxJson.success("保存成功", request, response).put("sysUser", sysUser.toSysUserView());
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户", description = "根据ID删除用户信息。", parameters = {@Parameter(name = "ids", description = "用户ID列表，多个ID用英文逗号分隔。")})
    public AjaxJson delete(@RequestParam String ids, HttpServletRequest request, HttpServletResponse response) {
        // 检查ID参数是否为空，为空则返回错误响应
        if (ids == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        // 调用服务层方法，执行删除操作
        sysUserService.delete(ids);
        // 返回成功响应
        return AjaxJson.success(request, response);
    }

    @PostMapping("/changePassword")
    @Operation(summary = "更改用户密码", description = "更改用户密码。")
    public AjaxJson changePassword(@RequestBody SysUser.SysUserChangePasswordDto sysUserChangePasswordDto, HttpServletRequest request, HttpServletResponse response) {

        SysUser sysUser = new SysUser(TokenUtil.getUid(request));
        sysUser.setPassword(sysUserChangePasswordDto.getNewPassword());
        if(sysUserService.getByIdAndPassword(TokenUtil.getUid(request),sysUserChangePasswordDto.getOldPassword())!=null){
            sysUserService.save(sysUser);
        }else{
            return AjaxJson.error("旧密码错误", HttpStatus.HTTP_UNAUTHORIZED, request, response);
        }
        // 返回成功响应
        return AjaxJson.success(request, response);
    }
}
